const { sqlOne, sqlBatch } = require("../db/common")

exports.UpdateOperator = async (req, res) => {
  // console.log(req.body);
  try {
    const results = await sqlOne("select * from commemorate where _id = ?", [req.body._id])
    let results2 = null
    if (results.length > 0) {
      // 修改
      console.log("修改");
      results2 = await sqlOne("update commemorate set ? where id=?", [{ _id: results[0]._id, is_lit: !results[0].is_lit, date: new Date() }, results[0].id])
    } else {
      // 不存在 插入
      results2 = await sqlOne("insert into commemorate set ?", { _id: req.body._id, is_lit: 1, date: new Date() })
    }
    return results2.affectedRows >= 1 ? res.onSuccess() : res.onError("失败")
  } catch (e) {
    console.log(e);
    res.onError();
  }
}

// 获取
exports.getOperator = async (req,res) => {
  const results = await sqlOne("select count(*) from commemorate where is_lit=1")
  const results2 = await sqlOne("select * from commemorate where _id = ?", [req.params._id])
  res.onSuccess({
    count: results[0]['count(*)'],
    commemorate:{
      _id:req.params._id,
      is_lit:0,
      date:null,
      ...(results2.length>0?results2[0]:{})
    }
  });
}